package com.agileai.portal.controller.wcm;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.bizmoduler.core.TreeAndContentManage;
import com.agileai.hotweb.controller.core.TreeAndContentManageEditHandler;
import com.agileai.hotweb.domain.FormSelect;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.wcm.InfomationManage;
import com.agileai.util.ListUtil;
import com.agileai.util.MapUtil;
import com.agileai.util.StringUtil;

public class WcmInfomationEditHandler
        extends TreeAndContentManageEditHandler {
    
	public WcmInfomationEditHandler() {
        super();
        this.serviceId = buildServiceId(InfomationManage.class);
        this.tabId = "WcmInfomation";
        this.columnIdField = "COL_ID";
        this.contentIdField = "INFO_ID";
    }
	
    @SuppressWarnings("unchecked")
	@PageAction
	public ViewRenderer addKeyWordsRef(DataParam param){
    	String responseText = "";
        InfomationManage infomationManage = getService();
        String infomationId = param.get("INFO_ID");
        List<DataRow> records = infomationManage.findInfomationKeyWordsRelations(infomationId);
		
		String keyWordsRefs = param.get("keyWordsRefs");
		String[] keyWordsArray = keyWordsRefs.split(",");
		List<String> keyWordsList = ListUtil.arrayToList(keyWordsArray);
		
		List<DataRow> pureMappingRefs = this.getFilteredList(records, keyWordsList, infomationId);
		if (pureMappingRefs.size() == 0){
			responseText = "alreadyAdded";
		}else{
			infomationManage.addInfomationKeyWordsRelation(infomationId,pureMappingRefs);
			FormSelect formSelect = this.buildRefKeyWordsSelect(param);
	        responseText = formSelect.getScriptSyntax("refKeyWords");			
		}
		return new AjaxRenderer(responseText);
	}
    
    private List<DataRow> getFilteredList(List<DataRow> records,List<String> keyWordsList,String infoId){
    	List<DataRow> result = new ArrayList<DataRow>();
    	if (records != null){
    		for (int i=0;i < keyWordsList.size();i++){
    			String wordId = keyWordsList.get(i);
    			if (!containWordId(records,wordId)){
    				DataRow row = new DataRow("WORD_ID",wordId,"INFO_ID",infoId);
        			result.add(row);    				
    			}
    		}
    	}else{
    		for (int i=0;i < keyWordsList.size();i++){
    			String wordId = keyWordsList.get(i);
    			DataRow row = new DataRow("WORD_ID",wordId,"INFO_ID",infoId);
    			result.add(row);
    		}
    	}
    	return result;
    }
    
    private boolean containWordId(List<DataRow> records,String wordId){
    	boolean result = false;
    	for (int i=0;i < records.size();i++){
    		DataRow row = records.get(i);
    		String tempWordId = row.getString("WORD_ID");
    		if (tempWordId.equals(wordId)){
    			result = true;
    			break;
    		}
    	}
    	return result;
    }
    
    @PageAction
	public ViewRenderer delKeyWordsRef(DataParam param){
    	String responseText = "";
		String INFO_ID = param.get("INFO_ID");
		String keyWordsRefs = param.get("refKeyWords");
		InfomationManage infomationManage = getService();
		infomationManage.delInfomationKeyWordsRelation(INFO_ID, keyWordsRefs);
        FormSelect formSelect = this.buildRefKeyWordsSelect(param);
        responseText = formSelect.getScriptSyntax("refKeyWords");
    	return new AjaxRenderer(responseText);
	}
	
    public ViewRenderer doSaveAction(DataParam param){
		String rspText = SUCCESS;
		TreeAndContentManage service = this.getService();
		String operateType = param.get(OperaType.KEY);
		if (OperaType.CREATE.equals(operateType)){
			String colIdField = service.getTabIdAndColFieldMapping().get(this.tabId);
			String columnId = param.get(this.columnIdField);
			param.put(colIdField,columnId);
			getService().createtContentRecord(tabId,param);	
		}
		else if (OperaType.UPDATE.equals(operateType)){
			getService().updatetContentRecord(tabId,param);	
		}
		rspText = param.get(this.contentIdField);
		return new AjaxRenderer(rspText);
	}
    
	@PageAction
    public ViewRenderer modifyInfomationState(DataParam param){
    	String responseText = FAIL;
    	String infomationId = param.get("infomationId");
    	String bizActionType = param.get("bizActionType");
    	InfomationManage infomationManage = this.getService();
    	User user = (User)getUser();
    	infomationManage.modifyInfomationState(infomationId, bizActionType,user);
    	responseText = SUCCESS;
    	return new AjaxRenderer(responseText);
    }
	
    protected void processPageAttributes(DataParam param) {
        setAttribute("INFO_AUTH_TYPE",
                     FormSelectFactory.create("WCM_AUTH_TYPE")
                                      .addSelectedValue(getOperaAttributeValue("INFO_AUTH_TYPE",
                                                                               "public")));
        setAttribute("INFO_STATE",
                     FormSelectFactory.create("WCM_INFO_STATE")
                                      .addSelectedValue(getOperaAttributeValue("INFO_STATE",
                                                                               "draft")));
        setAttribute("INFO_SETTOP",
                     FormSelectFactory.create("BOOL_DEFINE")
                                      .addSelectedValue(getOperaAttributeValue("INFO_SETTOP",
                                                                               "N")));
        setAttribute("INFO_SUPPORT_COMMENT",
                     FormSelectFactory.create("BOOL_DEFINE")
                                      .addSelectedValue(getOperaAttributeValue("INFO_SUPPORT_COMMENT",
                                                                               "Y")));
        setAttribute("INFO_COMMENT_ANONYMOUS",
                     FormSelectFactory.create("BOOL_DEFINE")
                                      .addSelectedValue(getOperaAttributeValue("INFO_COMMENT_ANONYMOUS",
                                                                               "Y")));
        User user = (User)getProfile().getUser();
        setAttribute("INFO_READ_COUNT",getAttributeValue("INFO_READ_COUNT","0"));
        setAttribute("INFO_SORT_NO",getAttributeValue("INFO_SORT_NO","0"));
        setAttribute("INFO_CREATER", getAttributeValue("INFO_CREATER",user.getUserCode()));
        setAttribute("INFO_CREATER_NAME", getAttributeValue("INFO_CREATER_NAME",user.getUserName()));
        setAttribute("INFO_CREATE_TIME", getAttribute("INFO_CREATE_TIME",new Date()));
  
        FormSelect formSelect = this.buildRefKeyWordsSelect(param);
        this.setAttribute("refKeyWords", formSelect);
        
        
		String operaType = param.get(OperaType.KEY);
		if (OperaType.UPDATE.equals(operaType) || OperaType.DETAIL.equals(operaType)){
			JSONArray jsonArray = this.buildInfoIdJsonArray(param);
	        FormSelect refInfoIdsSelect = this.buildRefInfoIdsSelect(param,jsonArray);
	        this.setAttribute("refInfoIds", refInfoIdsSelect);
		}
        
        String editMode = param.get("editMode"); 
        String userCode = user.getUserCode(); 
        this.getSessionAttributes().put(InfomationManageListHandler.LastEditTypeSessionKey, InfomationManage.EditType.Profile);
        this.setAttribute("editMode",editMode); 
        this.setAttribute("userCode",userCode); 
    }

    protected InfomationManage getService() {
        return (InfomationManage) this.lookupService(this.getServiceId());
    }
   
    private FormSelect buildRefKeyWordsSelect(DataParam param){
        InfomationManage infomationManage = getService();
        String infomationId = param.get("INFO_ID","-1");
        List<DataRow> records = infomationManage.findInfomationKeyWordsRelations(infomationId);
        if (records == null){
        	records = new ArrayList<DataRow>();	
        }
        FormSelect formSelect = new FormSelect();
        formSelect.setKeyColumnName("WORD_ID");
        formSelect.setValueColumnName("WORD_NAME");
        formSelect.putValues(records);
        formSelect.addHasBlankValue(false);
        return formSelect;
    }
    
	@PageAction
	public ViewRenderer addInfoIdsRef(DataParam param){
    	String responseText = "";
        InfomationManage infomationManage = getService();
        String newRelInfoId = param.get("newRelInfoId");
        JSONArray jsonArray = this.buildInfoIdJsonArray(param);
        boolean alreadyAdd = false;
        try {
            for (int i=0;i < jsonArray.length();i++){
            	JSONObject jsonObject = jsonArray.getJSONObject(i);
            	String infoId = jsonObject.getString("infoId");
            	if (infoId.equals(newRelInfoId)){
            		alreadyAdd = true;
            		break;
            	}
            }
    		if (alreadyAdd){
    			responseText = "alreadyAdded";
    		}else{
    			JSONObject jsonObject = new JSONObject();
    			jsonObject.put("infoId", newRelInfoId);
    			jsonArray.put(jsonObject);
    			
    			String infoId = param.get("INFO_ID");
    			infomationManage.updateInfoRelInfoIds(infoId, jsonArray.toString());
    			
    			FormSelect formSelect = this.buildRefInfoIdsSelect(param,jsonArray);
    	        responseText = formSelect.getScriptSyntax("refInfoIds");			
    		}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}    
    
    @PageAction
	public ViewRenderer delInfoIdsRef(DataParam param){
    	String responseText = "";
		String refInfoIds = param.get("refInfoIds");
		InfomationManage infomationManage = getService();
		JSONArray jsonArray = this.buildInfoIdJsonArray(param);
        try {
        	List<String> infoIdList = new ArrayList<String>();
            for (int i=0;i < jsonArray.length();i++){
            	JSONObject jsonObject = jsonArray.getJSONObject(i);
            	String infoId = jsonObject.getString("infoId");
            	if (infoId.equals(refInfoIds)){
            		continue;
            	}
            	infoIdList.add(infoId);
    		}
            
            JSONArray newJSONArray = listToRelInfoJson(infoIdList);
            String infoId = param.get("INFO_ID");
			infomationManage.updateInfoRelInfoIds(infoId, newJSONArray.toString());
			FormSelect formSelect = this.buildRefInfoIdsSelect(param,newJSONArray);
	        responseText = formSelect.getScriptSyntax("refInfoIds");	            
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
        return new AjaxRenderer(responseText);
	}	    
    
    @PageAction
	public ViewRenderer moveUpInfoIdsRef(DataParam param){
    	String responseText = "";
		String refInfoIds = param.get("refInfoIds");
		InfomationManage infomationManage = getService();
		JSONArray jsonArray = this.buildInfoIdJsonArray(param);
        try {
        	List<String> infoIdList = new ArrayList<String>();
            for (int i=0;i < jsonArray.length();i++){
            	JSONObject jsonObject = jsonArray.getJSONObject(i);
            	String infoId = jsonObject.getString("infoId");
            	if (infoId.equals(refInfoIds)){
            		infoIdList.add(i-1, infoId);
            	}else{
            		infoIdList.add(infoId);       		
            	}
    		}
            JSONArray newJSONArray = listToRelInfoJson(infoIdList);
            String infoId = param.get("INFO_ID");
			infomationManage.updateInfoRelInfoIds(infoId, newJSONArray.toString());
			FormSelect formSelect = this.buildRefInfoIdsSelect(param,newJSONArray);
	        responseText = formSelect.getScriptSyntax("refInfoIds");	            
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return new AjaxRenderer(responseText);
	}	    
    
    @PageAction
	public ViewRenderer moveDownInfoIdsRef(DataParam param){
    	String responseText = "";
		String refInfoIds = param.get("refInfoIds");
		InfomationManage infomationManage = getService();
		JSONArray jsonArray = this.buildInfoIdJsonArray(param);
        try {
        	List<String> infoIdList = new ArrayList<String>();
        	int matchIndex = 0;
        	for (int i=0;i < jsonArray.length();i++){
            	JSONObject jsonObject = jsonArray.getJSONObject(i);
            	String infoId = jsonObject.getString("infoId");
            	if (infoId.equals(refInfoIds)){
            		matchIndex = i;
            	}
            	infoIdList.add(infoId);	
    		}
        	infoIdList.remove(matchIndex);
        	infoIdList.add(matchIndex+1,refInfoIds);
            
            JSONArray newJSONArray = listToRelInfoJson(infoIdList);
            String infoId = param.get("INFO_ID");
			infomationManage.updateInfoRelInfoIds(infoId, newJSONArray.toString());
			FormSelect formSelect = this.buildRefInfoIdsSelect(param,newJSONArray);
	        responseText = formSelect.getScriptSyntax("refInfoIds");	            
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return new AjaxRenderer(responseText);
	}	
    
    private FormSelect buildRefInfoIdsSelect(DataParam param,JSONArray jsonArray){
    	FormSelect formSelect = new FormSelect();
        InfomationManage infomationManage = getService();
    	try {
            List<String> infoIdList = new ArrayList<String>();
            for (int i=0;i < jsonArray.length();i++){
            	JSONObject jsonObject = jsonArray.getJSONObject(i);
            	String infoId = jsonObject.getString("infoId");
            	infoIdList.add(infoId);
            }
        	List<DataRow> records = infomationManage.findRefInfoRecords(infoIdList);
            if (records == null){
            	records = new ArrayList<DataRow>();	
            }
            formSelect.setKeyColumnName("INFO_ID");
            formSelect.setValueColumnName("INFO_TITLE");
            formSelect.putValues(records);
            formSelect.addHasBlankValue(false); 				
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
        return formSelect;
    }
    
    private JSONArray buildInfoIdJsonArray(DataParam param){
    	JSONArray result = new JSONArray();
        InfomationManage infomationManage = getService();
        DataRow row = infomationManage.getContentRecord(this.tabId, param);
        if (!MapUtil.isNullOrEmpty(row)){
            String relInfoIds = row.getString("INFO_REL_INFOIDS");
            try {
            	if (!StringUtil.isNullOrEmpty(relInfoIds)){
            		result = new JSONArray(relInfoIds);
            	}
			} catch (Exception e) {
				log.error(e.getLocalizedMessage(),e);
			}    
        }
		return result;
    }
    
    private JSONArray listToRelInfoJson(List<String> infoIdList){
    	JSONArray result = new JSONArray();
    	try {
        	for (int i=0;i < infoIdList.size();i++){
        		String infoId = infoIdList.get(i);
        		JSONObject jsonObject = new JSONObject();
        		jsonObject.put("infoId", infoId);
        		result.put(jsonObject);
        	}			
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return result;
    }
}
